﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;

namespace KC.Library.Net
{
	public class Mail
    {
		/// <summary>Sends an email.</summary>
		/// <param name="FromAddr">Email address of sender</param>
		/// <param name="FromName">Friendly name of sender</param>
		/// <param name="To">Email address(es) of recipient(s), comma/semicolon delimited</param>
		/// <param name="cc">Email address(es) of CC recipient(s), comma/semicolon delimited</param></param>
		/// <param name="bcc">Email address(es) of BCC recipient(s), comma/semicolon delimited</param></param>
		/// <param name="subject">Message subject</param>
		/// <param name="body">Message body in plaintext or HTML format</param>
		/// <param name="SmtpServer">SMTP Server IP or hostname</param>
		/// <param name="username">SMTP Server username, if SSL; else null</param>
		/// <param name="password">SMTP Server password, if SSL; else null</param>
		public async static Task SendMail(string FromAddr, string FromName, string To, string cc, string bcc, string subject, string body, string SmtpServer, string username, string password)
		{
			Task t = null;
			using (MailMessage message = new MailMessage() { From = new MailAddress(FromAddr, FromName, Encoding.UTF8), Subject = subject, Body=body, IsBodyHtml=true, SubjectEncoding = Encoding.UTF8, BodyEncoding=Encoding.UTF8 }) {
				await Task.Run(() => {
					if (To != null && To.Trim().Length > 0)
						foreach (string to in To.Split(new char[] { ',', ';' }))
							message.To.Add(to);
					if (cc != null && cc.Trim().Length > 0)
						foreach (string to in cc.Split(new char[] { ',', ';' }))
							message.CC.Add(to);
					if (bcc != null && bcc.Trim().Length > 0)
						foreach (string to in bcc.Split(new char[] { ',', ';' }))
							message.Bcc.Add(to); });

				using (SmtpClient client = string.IsNullOrEmpty(username)
					? new SmtpClient(SmtpServer) { Port = 587 }
					: new SmtpClient(SmtpServer) { EnableSsl = true, Port = 587, Credentials = new System.Net.NetworkCredential(username, password) }) {
					t = Task.Run(() => client.Send(message));
					await t; } }
			if (t != null && t.Exception != null)
				throw t.Exception;
		}
	}
}
